package by.msokoloff.javaweb2015.services.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.springframework.stereotype.Service;

import by.msokoloff.javaweb2015.dataaccess.CityDao;
import by.msokoloff.javaweb2015.datamodel.Airport;
import by.msokoloff.javaweb2015.datamodel.Airport_;
import by.msokoloff.javaweb2015.datamodel.City;
import by.msokoloff.javaweb2015.datamodel.City_;
import by.msokoloff.javaweb2015.services.AirportService;
import by.msokoloff.javaweb2015.services.CityService;

@Service
public class CityServiceImpl implements CityService {

	@Inject
	private CityDao dao;

	@Inject
	private AirportService airportService;

	@Override
	public City get(Integer id) {
		return dao.getById(id);
	}

	@Override
	public List<City> getByField(SingularAttribute<City, ?> attr, Object val) {
		return dao.getByField(attr, val);
	}

	@Override
	public List<City> getAll() {
		return dao.getAll();
	}

	@Override
	public void createOrUpdate(City city) {
		if (city.getId() == null) {
			dao.create(city);
		} else {
			dao.update(city);
		}
	}

	@Override
	public void delete(City city) {
		dao.delete(city.getId());
	}

	@Override
	public void deleteAll() {
		dao.deleteAll();
	}

	@Override
	public Long getCount() {
		return dao.getCount();
	}

	@Override
	public List<City> getAll(SingularAttribute<City, ?> attr, boolean ascending, int startRecord, int pageSize) {
		return dao.getAll(attr, ascending, startRecord, pageSize);
	}

	@Override
	public void deleteWithRelations(City city) {
		List<Airport> relatedAirports = airportService.getByField(Airport_.city, city);
		for (Airport airport : relatedAirports) {
			airportService.deleteWithRelations(airport);
		}
		delete(city);
	}

	@Override
	public long getCountByField(SingularAttribute<City, ?> attr, Object val) {
		return dao.getCountByField(attr, val);
	}

	@Override
	public List<City> getAll(SingularAttribute<City, ?> filterAttr, Object val, SingularAttribute<City, ?> attr, boolean ascending, int startRecord, int pageSize) {
		return dao.getAll(filterAttr, val, attr, ascending, startRecord, pageSize);
	}

	@Override
	public List<City> getStartingWith(String string, Integer max) {
		return dao.getStartingWith(City_.name, string, max);
	}

}
